package com.polaris.live.ui.game

import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import com.lxj.xpopup.XPopup
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.databinding.FragmentGameWebBinding
import com.polaris.live.im.manager.ImNoticeManager
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.popup.party.CloseGamePopup
import com.polaris.live.resp.back_resp.GameVo
import com.polaris.live.resp.bean.GameExtBean
import com.polaris.live.resp.bean.YomiGameExtBean

/**
 * GameWebFragment
 * @author Created by 天晴 on 2024/1/18 15:38
 * @since 1.0.0
 **/
class GameWebFragment : DialogFragment() {

    private val gameVo: GameVo? by lazy {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getParcelable("gameVo", GameVo::class.java)
        } else {
            arguments?.getParcelable("gameVo")
        }
    }
    private val gameMode: String by lazy {
        arguments?.getString("gameMode") ?: GameUtils.HALF_SCREEN
    }
    private val roomId: String by lazy {
        arguments?.getString("roomId") ?: ""
    }

    private val extBean: GameExtBean? by lazy {
        gameVo?.ext?.let { JsonUtils.fromJson(it, GameExtBean::class.java) }
    }

    private val yomiExtBean: YomiGameExtBean? by lazy {
        gameVo?.ext?.let { JsonUtils.fromJson(it, YomiGameExtBean::class.java) }
    }

    private lateinit var mBinding: FragmentGameWebBinding
    private lateinit var mViewModel: BaseViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel = ViewModelProvider(this)[BaseViewModel::class.java]
        GameUtils.start()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        mBinding = FragmentGameWebBinding.inflate(inflater, container, false)
        mBinding.root.setBackgroundColor(0)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        dialog?.setOnKeyListener { _, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP) {
                showPop()
                return@setOnKeyListener true
            }
            false
        }
        initView()
        initListene()
    }

    private fun initListene() {
        //因为yomi的游戏点击游戏外的区域没有任何效果，所以加上了是否要关闭的弹窗
        if (isYomiGame()) {
            mBinding.llContent.setOnSingleClickListener {
                showPop()
            }
        }
    }

    private fun initView() {
        gameVo?.let {
            mBinding.gameView.initWeb(requireActivity(), it, gameMode, roomId,
                recharge = {
                    GlobalPopupManager.showRechargePopup(
                        requireContext(),
                        mViewModel,
                        isNeedBottom = true,
                        onRechargeOk = { re ->
                            if (re == true) {
                                mBinding.gameView.walletUpdate(UserManager.getUserId())
                                UserManager.getUser().account?.userCoins?.let { coin ->
                                    mBinding.gameView.onBalanceUpdate(coin)
                                }
                            }
                        }
                    )
                },
                destroy = {
                    if (isHalfWindow() && isHasHalfWindow()) {
                        showPop()
                    } else {
                        dismiss()
                    }
                })
        }
        //余额变动
        ImNoticeManager.observeAccountChange(this) {
            mBinding.gameView.walletUpdate(UserManager.getUserId())
        }

        if (gameVo?.providerType == AppConst.GameType.YOMI) {
            //yomi的游戏写死宽高，计算960在屏幕上的比例
            mBinding.gameView.post {
                setRecommendedHeight(mBinding.gameView, 960)
            }
        }
    }

    fun setRecommendedHeight(view: View, recommendedPx: Int) {
        val screenHeight = view.context.resources.displayMetrics.heightPixels
        val ratio = recommendedPx.toFloat() / screenHeight // 计算推荐高度占屏幕的比例
        val adjustedHeight = (screenHeight * ratio).toInt()
        val params = view.layoutParams
        params.height = adjustedHeight
        view.layoutParams = params
    }

    private fun isHalfWindow() = gameMode == GameUtils.HALF_SCREEN || gameMode == GameUtils.HALF_SCREEN2

    private fun isHasHalfWindow() = extBean?.hasHalfWindow == 1 || yomiExtBean?.hasHalfWindow == 1

    private fun isYomiGame() = gameVo?.providerType == AppConst.GameType.YOMI


    fun showPop() {
        XPopup.Builder(requireContext())
            .navigationBarColor(R.color.color_fa1d1928)
            .isDestroyOnDismiss(true)
            .asCustom(
                CloseGamePopup(
                    requireContext(),
                    gameVo?.exitExplain ?: "",
                    cancel = {

                    },
                    ok = {
                        dismiss()
                    })
            )
            .show()
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = Dialog(requireContext(), android.R.style.Theme_Light_NoTitleBar_Fullscreen)
        val window = dialog.window
        window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        return dialog
    }

    override fun onPause() {
        mBinding.gameView.onPause()
        super.onPause()
    }

    override fun onResume() {
        mBinding.gameView.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        GameUtils.finish()
        mBinding.gameView.onDestroy()
    }
}